#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "server.h"

char* module_dir = "./modules";

struct server_module* module_open (const char* module_name){
    char* module_path = (char*)xmalloc(strlen(module_dir) + strlen(module_name) + 2);
    sprintf(module_path,"%s/%s",module_dir,module_name);
    
    void* handle = dlopen(module_path,RTLD_NOW);
    free(module_path);
    if(!handle)  return NULL;
    Fun fun = dlsym(handle,"module_generate");
    if(!fun) {
        dlclose(handle);
        return NULL;
    }

    struct server_module* module = xmalloc(sizeof(struct server_module));
    module->name = xstrdup(module_name);
    module->handle = handle;
    module->generate_function = fun;
    return module;
}

void module_close (struct server_module* module)
{
    /* Close the shared library. */
    dlclose (module->handle);
    /* Deallocate the module name. */
    free ((char*) module->name);
    /* Deallocate the module object. */
    free (module);
}